package cn.afactory.tygz.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.harwkin.nb.camera.PageBigImageActivity;
import com.harwkin.nb.camera.model.PicsItem;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.model.SnsCommentInfo;
import cn.afactory.tygz.model.SnsSubjectDetail;
import cn.afactory.tygz.model.SnsSubjectDetailList;
import cn.afactory.tygz.model.UserInfo;
import cn.afactory.tygz.ui.base.adapter.NearByForumsAdapter;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshBase;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshListView;
import cn.afactory.tygz.ui.base.utils.DialogUtil;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.base.utils.sns.TimeUtil;
import cn.afactory.tygz.ui.sns.PublishSubjectActivity;
import cn.afactory.tygz.ui.sns.SubjectDetailActivity;
import cn.afactory.tygz.ui.sns.UserProfileActivity;
import cn.afactory.tygz.ui.sns.controller.SnsControler;

/**
 * Created by Kenneth on 15/9/17.
 */
public class ProfileUserSubjectFragment extends cn.afactory.tygz.ui.base.BaseFragment implements NearByForumsAdapter.OnItemClickListener{

    private UserInfo userInfo;
    private SnsControler mController;
    private NearByForumsAdapter mAdapter;
    private List<SnsSubjectDetail> mList = new ArrayList<SnsSubjectDetail>();

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SnsControler.MSG_GET_USER_FORUMS_OK:
                if (msg.obj instanceof SnsSubjectDetailList) {
                    hideErrorPage(-1);
                    SnsSubjectDetailList t = (SnsSubjectDetailList) msg.obj;
                    if (t.rows != null && t.rows.size() >= 0) {
                        try {
                            if (msg.arg1 == SnsControler.MSG_DATA_FROM_CACHE && mAdapter.getCount() == 0 && mLastReqTime == 0) {
                                mList.addAll(t.rows);
                            } else {
                                if (mLastReqTime == 0) {
                                    mList.clear();
                                }
                                mList.addAll(t.rows);
                                mLastReqTime = t.rows.get(t.rows.size() - 1).addTime;
                            }

                            mAdapter.setData(mList);
                            mPageIndex = (mList.size() / mPageSize) + 1;

                            if (plistview.isRefreshing()) {
                                plistview.onRefreshComplete();
                            }
                            if (t.rows.size() < mPageSize) {
                                plistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            } else {
                                plistview.setMode(PullToRefreshBase.Mode.BOTH);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (mAdapter.getCount() == 0) {
                            showNullPage(true);
                        }
                    }
                }
                break;
            case SnsControler.MSG_GET_USER_FORUMS_KO:
                if (mAdapter.getCount() == 0) {
                    hideErrorPage(-1);
                    showErrorPage(msg.arg1, new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            startLoadDatas();
                        }
                    });
                } else {
                    LocalUtils.showToast(mContext, "获取附近的动态失败！");
                }
                break;
            default:
                break;
        }
        // 结束下拉刷新
        if (plistview.isRefreshing()) {
            plistview.onRefreshComplete();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mController = new SnsControler(mContext,mUIHandler,"UserSubject");

        if (null != getArguments()) {
            userInfo = (UserInfo)getArguments().getSerializable(UserProfileActivity.USER_INFO_TAG);
        }
        if (null != userInfo) {
            addTitleBar = false;
        } else {
            addTitleBar = true;
        }
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fg_profile_user_subject, null);
        initViews(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
    }

    private void initViews(View v){

        if (addTitleBar) {
            setTitleText("我关注的帖子");
        }

        plistview = (PullToRefreshListView)v.findViewById(R.id.lv_forums_list);

        mAdapter = new NearByForumsAdapter(getActivity(),mList);
        plistview.setAdapter(mAdapter);

        plistview.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListView lv = plistview.getRefreshableView();
                if (position >= lv.getHeaderViewsCount()) {
                    position -= lv.getHeaderViewsCount();
                }
                SnsSubjectDetail snsSubjectDetail = (SnsSubjectDetail) mAdapter.getItem(position);
                Intent intent = new Intent(mContext, SubjectDetailActivity.class);
                intent.putExtra(SubjectDetailActivity.SUBJECT_DETAIL_TAG, snsSubjectDetail);
                startActivity(intent);
            }
        });

        mAdapter.setItemClickListener(this);

        plistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadDatas();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadSubjectData(false);
            }
        });
    }

    private void initData(){
        startLoadDatas();
    }

    private void startLoadDatas(){
        startLoadSubjectData(true);
    }

    /**
     * 加载listview数据
     */
    private int mPageIndex = 1;
    private int mPageSize = 10;
    private long mLastReqTime = System.currentTimeMillis();
    protected void startLoadSubjectData(boolean cleanData) {
        if (cleanData) {
            mPageIndex = 1;
            mLastReqTime = 0;
            mList.clear();
        }
        if (null == userInfo) {
            //我关注的帖子
            mController.loadUserJoinedForumsList(SPUtils.getUid(mContext), mPageIndex, mPageSize);
        } else {
            //其他用户关注的帖子
            mController.loadUserJoinedForumsList(userInfo.id, mPageIndex, mPageSize);
        }
    }

    @Override
    public void onPraise(TextView v, SnsSubjectDetail item) {
        if (TimeUtil.isFastDoubleClick()) {
            return;
        }
        if (item != null && item.id >= 0) {
            mController.doPraiseToSubject(v, item);
        }
    }

    @Override
    public void onClickImage(int position, List<String> mPath) {
        if (TimeUtil.isFastDoubleClick()) {
            return;
        }
        if (mPath != null) {
            ArrayList<PicsItem> list = new ArrayList<>();
            for (String tmp : mPath) {
                PicsItem picsItem = new PicsItem();
                picsItem.image = tmp;
                list.add(picsItem);
            }
            mContext.startActivity(PageBigImageActivity.getIntent(mContext, list, position, false, false));
        }
    }


    @Override
    public void onClickTopic(String topic, long topicId) {
        NaviUtils.gotoTopicDetailActivity(mContext, topicId);
    }

    @Override
    public void onClickShare(SnsSubjectDetail item) {
        DialogUtil.showShareDialog(getActivity(), "分享Title",
                item.content,
                null,
                null,
                null,
                null,
                null,
                null);
    }

    @Override
    public void onClickSubjectList(String str) {

    }

    @Override
    public void onClickIcon(SnsSubjectDetail item) {
        NaviUtils.gotoUserProfileActivity(getActivity(), item.userId, item.nickName);
    }

    @Override
    public void onClickCommentIcon(SnsCommentInfo commentInfo) {
        NaviUtils.gotoUserProfileActivity(getActivity(), commentInfo.userId, commentInfo.userName);
    }
}